<template>

  <textarea
      class="input_none"
      v-model="textarea2"
      placeholder="这一时刻的想法"
  />

  <el-upload
      v-model:file-list="fileList"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :auto-upload="false"
      :on-change="uploadFile"
      multiple
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>

  <div style="width: 100%;text-align: center;margin-top: 20px">
    <el-button type="success" style="width: 200px" @click="add">发表</el-button>
  </div>

</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import {UploadFile, UploadFiles} from "element-plus";
import {FileType} from "../../utils/constant";
import {upload} from "../../service/FileApi";
import {error, success} from "../../utils/messageUtil";
import {release} from "../../service/ShowApi";
import {useRouter} from "vue-router";
const router = useRouter();

const textarea2 = ref('')

const add= () => {
  if(fileRo.multipartFiles.length === 0){
    release({
      text: textarea2.value,
    }).then(d => {
      if (d.data.code == 200) {
        success("发布成功")
      } else {
        error(d.data.message)
      }
    }).catch(() => {
      error("网络错误")
    })
  }else {
    upload(fileRo).then(d => {
      if (d.data.code == 200) {
        //发布
        release({
          text: textarea2.value,
          images: d.data.date.fileIds
        }).then(d => {
          if (d.data.code == 200) {
            success("发布成功")
            router.push({
              name: 'show'
            })
          } else {
            error(d.data.message)
          }
        }).catch(() => {
          error("网络错误")
        })
      } else {
        error(d.data.message)
      }
    }).catch(() => {
      error("网络错误")
    })
  }
}

const fileRo: any = {
  multipartFiles: [],
  fileType: FileType.SHOW
}

const uploadFile = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  fileRo.multipartFiles.push(uploadFile.raw)
}

const fileList = ref<UploadUserFile[]>([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  fileRo.multipartFiles.splice(fileRo.multipartFiles.indexOf(uploadFile.raw), 1)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
</script>

<style scoped>
.input_none{
  background-color:transparent;
  border:0;
  outline:none;
  width: 100%;
  height: 400px;
  font-size: 30px;
}
</style>